# -*- coding:utf-8 -*-

# @Time    : 2023/5/16 02:21
# @Author  : zengwenjia
# @Email   : zengwenjia@lingxi.ai
# @File    : generate_bot_dialogue.py
# @Software: LLM_internal

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import asyncio
import os

import pandas as pd
from loguru import logger
from bot.insurance_consultant_dx.sales import Sales
import traceback

#根据真实用户对话记录生成数据
async def bot_dialogue_by_truth_conversation(path, taget_num=100):
    deal_results = get_deal_data(path)
    results = deal_results[:]
    try:
        i = 0
        for result in results:
            session_id = str(result['session_id'])
            print(session_id)
            gpt = ''
            user_base_info = f"姓名:{result['姓名']+result['称呼']}\n年龄:{str(result['年龄'])}\n'地区':{result['地区']}"
            username = f"姓名:{result['姓名']+result['称呼']}"
            context = []
            for conversation in result["conversations"]:
                bot = Sales()
                conversation_dict = {}
                if conversation["role"] == "销售员":
                    conversation_dict["role"] = "assistant"
                    value = conversation["value"]
                    conversation_dict["content"] = value
                    conversation_dict['gpt'] = gpt
                    if "再见" in value or "拜拜" in value:
                        break
                    context.append(conversation_dict)

                elif conversation["role"] == "用户":
                    conversation_dict["role"] = "user"
                    conversation_dict["content"] = conversation["value"]
                    context.append(conversation_dict)
                    logger.info(f"session_id:{session_id},context:{context}")
                    gpt = await bot.async_reply_web(context, session_id, name=username, user_base_info=user_base_info, content=conversation["value"])
                    if "再见" in gpt or "拜拜" in gpt:
                        break
                i = i + 1
                print(i)
            pd.DataFrame(context).to_csv(f'../data_set/线上对话文本{session_id}时间{datetime.datetime.now().strftime("%Y%m%d-%H%M%S")}.csv', index=False, encoding='utf-8')
    except Exception as e:
        traceback.print_exc()
        # 打印堆栈
        print(e)



def get_deal_data(path):
    datas = []
    for csv_path in path:
        if os.path.isdir(csv_path):
            for file in os.listdir(csv_path):
                if not file.endswith('.csv'):
                    continue
                df = pd.read_csv(csv_path + file)
                faqDictList = df.to_dict('records')
                datas.extend(faqDictList)
        else:
            df = pd.read_csv(csv_path)
            faqDictList = df.to_dict('records')
            datas.extend(faqDictList)

    all_sessions = {}
    for index, faq in enumerate(datas):
        sessionId = str(faq['session_id'])
        if sessionId not in all_sessions:
            all_sessions[sessionId] = []
            # all_sessions[sessionId].append({"role": "用户", "value": "你好。"})
        all_sessions[sessionId].append({
            "role": str(faq['角色']),
            "姓名": str(faq['姓名']),
            "性别": str(faq['性别']),
            "称呼": str(faq['称呼']),
            "年龄": str(faq['年龄']),
            "地区": str(faq['地区']),
            "value": str(faq['过滤文本']),
        })

    all_sessions_new = []
    for session_id, session_value in all_sessions.items():
        sessions_dict = {}
        new_session_value = []
        #合并临近相同角色的内容
        for session_record in session_value:
            if len(new_session_value) == 0:
                new_session_value.append(session_record)
            else:
                if session_record['role'] == new_session_value[-1]['role']:
                    new_session_value[-1]['value'] += session_record['value']
                else:
                    new_session_value.append(session_record)

        if len(new_session_value) > 4:
            sessions_dict["session_id"] = session_id
            sessions_dict["age"] = session_id
            sessions_dict["conversations"] = new_session_value
            sessions_dict['姓名'] = session_value[0]['姓名']
            sessions_dict['性别'] = session_value[0]['性别']
            sessions_dict['称呼'] = session_value[0]['称呼']
            sessions_dict['年龄'] = session_value[0]['年龄']
            sessions_dict['地区'] = session_value[0]['地区']
            all_sessions_new.append(sessions_dict)


    return all_sessions_new




if __name__ == '__main__':
    import datetime
    # now_date = datetime.datetime.now().strftime("%Y-%m-%d")
    file_path = ["../internal_server/bot/insurance_consultant_dx/data/纯机对话文本-格式化.csv"]
    asyncio.run(bot_dialogue_by_truth_conversation(file_path))


